package com.heima.behavior.service.iml;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.CollectionBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {


    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    /*
    * 收藏
    * */
    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        //1. 校验参数 需要登录 文章id不能null  操作类型 0 或 1
        //2. 查询行为实体数据
        ApBehaviorEntry abId = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"没有对应行为实体");
        }
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApCollection one = mongoTemplate.findOne(query, ApCollection.class);
        if (one !=null &&  dto.getOperation().intValue()==0){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"请勿重复点收藏");
        }
        // 4. 没有点则 像mongo点赞集合中 添加喜欢数据
        if (dto.getOperation().intValue()==0){
            ApCollection apCollection = new ApCollection();
            apCollection.setArticleId(dto.getArticleId());
            apCollection.setCollectionTime(new Date());
            apCollection.setType((short) 0);
            apCollection.setEntryId(abId.getId());
            mongoTemplate.save(apCollection);
        }else {
            // 5. 如果是取消收藏操作  在mongo收藏集合中 删除对应收藏数据
            mongoTemplate.remove(query,ApCollection.class);
        }
        return ResponseResult.okResult();
    }
}
